﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KingsSharp.Core.Data.Entity.Migrations
{
    /// <summary>
    /// 数据库初始化策略
    /// </summary>
    /// <typeparam name="TContext"></typeparam>
    public class BaseDatabaseInitializer<TContext, TMigrationsConfiguration> :
        IDatabaseInitializer<TContext>
        where TContext : DbContext
        where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()
    {
        public void InitializeDatabase(TContext context)
        {
            try
            {
                if (!context.Database.Exists())
                {
                    CreateDatabaseIfNotExistsWithSeed<TContext> create = new CreateDatabaseIfNotExistsWithSeed<TContext>();
                    create.InitializeDatabase(context);
                }
                else
                {
                    //MigrateDatabaseToLatestVersion<DefualtDbContext, DefualtMigrationsConfiguration> update
                    //    = new MigrateDatabaseToLatestVersion<DefualtDbContext, DefualtMigrationsConfiguration>();

                    MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration> update
                      = new MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration>(true);

                    update.InitializeDatabase(context);
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }
}
